package com.dpteam.service.impl;

import com.dpteam.bean.MemberInfo;
import com.dpteam.bean.UserInfo;
import com.dpteam.dao.MemberDao;
import com.dpteam.dao.MemberLevelDao;
import com.dpteam.dao.UserDao;
import com.dpteam.model.Member;
import com.dpteam.model.MemberLevel;
import com.dpteam.model.User;
import com.dpteam.service.MemberService;
import com.dpteam.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by YangZhi on 2016/1/11.
 */
@Service
@Transactional
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberDao memberDao;

    @Resource
    private UserDao userDao;

    @Resource
    private MemberLevelDao memberLevelDao;

    private Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Override
    public int addMember(Member member) {
        logger.info("addMember:{}",member);
        //1.判断手机号是否已注册
        Member mem = memberDao.findByPhone(member.getPhone());
        if(mem != null) return 0;//已注册
        return (int)memberDao.save(member);
    }

    @Override
    public Member findByPhone(String phone) {
        logger.info("findMemberByPhone:{}",phone);
        return memberDao.findByPhone(phone);
    }

    @Override
    public Member findByIDCard(String IDCard) {
        logger.info("findByIDCard:{}",IDCard);
        return memberDao.findByIDCard(IDCard);
    }

    @Override
    public int addIntegralById(Integer memberId, Integer addCount) {
        logger.info("addIntegralById:{},{}",memberId,addCount);
        Member member = memberDao.get(Member.class,memberId);
        member.setIntegral(member.getIntegral() + addCount);
        member.setAllIntegral(member.getAllIntegral() + addCount);
        return (int)memberDao.save(member);
    }

    @Override
    public int clearIntegralById(Integer memberId) {
        logger.info("clearIntegralById:{}",memberId);
        Member member = memberDao.get(Member.class,memberId);
        if(member == null)return 0;
        member.setAllIntegral(0);
        return (int)memberDao.save(member);

    }

    @Override
    public int minusIntegralById(Integer memberId, Integer minusCount) {
        logger.info("minusIntegralById:{},{}",memberId,minusCount);
        Member member = memberDao.get(Member.class,memberId);
        if(member == null)return 0;
        member.setIntegral(member.getIntegral() + minusCount);
        return (int)memberDao.save(member);
    }

    @Override
    public List<Member> findByUserId(Integer casherId) {
        logger.info("findByUserId:{}", casherId);
        String hql = "from Member m where m.user.id = ?";
        return memberDao.find(hql,casherId);
    }

    @Override
    public List<Member> findAll() {
        logger.info("查询全部会员");
        return memberDao.findAll();
    }

    @Override
    public List<Member> findAllByPage(Page page) {
        logger.info("查询全部会员分页");
        return memberDao.findAllByPage(page);
    }

    @Override
    public List<MemberInfo> find(String phone) {
        logger.info("通过手机号查询会员 [phone:{}]", phone);
        List<MemberInfo> memberInfos = new ArrayList<>();
        if (phone != null && StringUtil.isNotEmpty(phone)) {
            Member member = memberDao.findByPhone(phone);
            memberInfos.add(TransformUtil.fromMember(member));
        } else {
            List<Member> members = memberDao.findAll();
            for (Member member : members) {
                memberInfos.add(TransformUtil.fromMember(member));
            }
        }
        return memberInfos;
    }

    @Override
    public boolean add(String name, int sex, String IDCardNo, String phone, int userId) {
        logger.info("添加会员[name:{},sex:{},IDCardNo:{},phone:{},userId:{},]", name, sex, IDCardNo, phone, userId);
        //TODO 参数校验
        Member member = new Member();
        User user = userDao.get(User.class, userId);
        if (user == null) {
            Subject subject = SecurityUtils.getSubject();
            UserInfo userInfo = (UserInfo)subject.getSession().getAttribute(Constant.currentUserKey);
            user = userDao.get(User.class, userInfo.getId());
        }
        member.setName(name);
        member.setGender(sex);
        member.setIDCard(IDCardNo);
        member.setPhone(phone);
        member.setUser(user);
        member.setAllIntegral(0);
        member.setIntegral(0);
        member.setRegisttime(LocalDateTime.now());
        MemberLevel level = memberLevelDao.findByLevel(MemberLv.LEVEL1);
        member.setMemberLevel(level);

        memberDao.save(member);
        return true;
    }

    @Override
    public void update(int memberId, String name, String phone, String IDCard) {
        Member member = memberDao.get(Member.class,memberId);
        member.setName(name);
        member.setPhone(phone);
        member.setIDCard(IDCard);
        memberDao.saveOrUpdate(member);
    }

    @Override
    public List<MemberInfo> findAll(Page page) {
        List<Member> members = memberDao.findAllByPage(page);
        List<MemberInfo> memberInfos = new ArrayList<>();
        for (Member member : members) {
            memberInfos.add(TransformUtil.fromMember(member));
        }
        return memberInfos;
    }
}
